import 'package:flutter/cupertino.dart';
import 'package:wan_android_flutter/repository/Api.dart';
import '../../repository/datas/home_banner_model.dart';
import '../../repository/datas/home_list_model.dart';

class HomeViewModel with ChangeNotifier {
  int pageIndex = 0;
  List<HomeBannerModel?>? bannerList;

  List<HomeListItemData>? dataList = [];

  Future getBanner() async {
    bannerList = await Api.instance().getBanner() ?? [];
    notifyListeners();
  }

  Future initDataList(bool loadMore,{ValueChanged<bool>? callBack}) async {
    if (loadMore) {
      pageIndex++;
    } else {
      dataList?.clear();
      pageIndex = 0;
    }
    //获取置顶列表
    getHotList(loadMore).then((onValue) {
      dataList?.addAll(onValue ?? []);
      //获取普通列表
      getHomeList(loadMore).then((onValue) {
        dataList?.addAll(onValue ?? []);
        //通知刷新
        notifyListeners();
        //回调
        callBack?.call(loadMore);
      });
    });
  }

  Future<List<HomeListItemData>?> getHomeList(bool loadMore) async {
    List<HomeListItemData>? list =
        await Api.instance().getHomeList("$pageIndex") ?? [];
    if (list.isNotEmpty) {
      return list;
    } else {
      if (loadMore && pageIndex > 0) {
        pageIndex--;
      }
    }
    return [];
  }

  Future<List<HomeListItemData>?> getHotList(bool loadMore) async {
    return loadMore ? [] : await Api.instance().getHotList() ?? [];
  }
  Future collect(String? id,int index,bool isCollect) async{
    bool? success ;
    if(isCollect == true){
      success = await Api.instance().collect(id);
    }else{
      success = await Api.instance().unCollect(id);
    }
    if(success == true){
      dataList?[index].collect = isCollect;
      notifyListeners();
    }
  }
}
